﻿using Xceed.Document.NET;

using DrawingColor = System.Drawing.Color;
using XceedFont = Xceed.Document.NET.Font;

namespace FireCounter;

internal static class CellEx
{
    public static readonly Formatting Formatting = new() {
        FontFamily = new XceedFont("宋体"),
        Size = 9,
        FontColor = DrawingColor.Black,
        Bold = false,
        Italic = false
    };

    public static void Center(this Cell cell)
    {
        cell.VerticalAlignment = VerticalAlignment.Center;

        foreach (var paragraph in cell.Paragraphs)
        {
            paragraph.Alignment = Alignment.center;
        }
    }

    public static void Clear(this Cell cell)
    {
        while (cell.Paragraphs.Count > 0)
        {
            cell.RemoveParagraphAt(0);
        }
    }

    public static string GetPlainText(this Cell cell)
    {
        return GetText(cell, "");
    }

    public static string GetText(this Cell cell, string sep = "\n")
    {
        return String.Join(sep, cell.Paragraphs.Select(p => p.Text)).Trim();
    }

    public static void Trim(this Cell cell)
    {
        var ps = new List<Paragraph>();

        foreach (var p in cell.Paragraphs)
        {
            if (String.IsNullOrWhiteSpace(p.Text))
            {
                ps.Add(p);
            }
        }

        foreach (var p in ps)
        {
            cell.RemoveParagraph(p);
        }

        foreach (var p in cell.Paragraphs)
        {
            var options = new StringReplaceTextOptions {
                SearchValue = p.Text,
                NewValue = p.Text.Trim(),
                NewFormatting = Formatting
            };

            p.ReplaceText(options);
        }

        if (cell.Paragraphs.Count == 0)
        {
            cell.InsertParagraph();
        }
    }
}
